﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using System.Windows;
using System.Windows.Input;
using AccountManagement.BussinessObjects;
using AccountManagement.DataAccess;
using Microsoft.Win32;
using Microsoft.Windows.Controls.Ribbon;

namespace AccountManagement
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private List<tblPhieuThuChi> _lstThuChi;

        public MainWindow()
        {
            InitializeComponent();
            _lstThuChi = new List<tblPhieuThuChi>();
        }

        private void CompanyConfig(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                var frmCompany = new FrmCompany();
                frmCompany.Owner = this;
                frmCompany.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frmCompany.ShowInTaskbar = false;
                frmCompany.ShowDialog();
            }
            catch (Exception)
            {
                
            }
        }

        private void RibbonWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                LoadData();
                PopulateCombobox();
            }
            catch (Exception)
            {
                
            }
        }

        public void LoadData()
        {
            try
            {
                var objIncomingBO = new IncomingBO();
                _lstThuChi = objIncomingBO.GetAll();

                // Add filters
                //var tmp = dgMain.Columns[1].HeaderStyle;
                //var a = tmp.TargetType;

                dgMain.ItemsSource = _lstThuChi;

                btnEditThu.IsEnabled = false;
                btnDeleteThu.IsEnabled = false;
                btnEditChi.IsEnabled = false;
                btnDeleteChi.IsEnabled = false;
            }
            catch (Exception)
            {
                
            }
        }

        private void AddCommand_Thu_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                var frmThu = new FrmThuChi(true);
                frmThu.Owner = this;
                frmThu.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frmThu.ShowInTaskbar = false;
                frmThu.ShowDialog();
            }
            catch (Exception)
            {

            }
        }

        private void EditCommand_Thu_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                var objPhieuThuChi = (tblPhieuThuChi)dgMain.SelectedItem;
                if (objPhieuThuChi == null) return;

                var frmThu = new FrmThuChi(objPhieuThuChi,true);
                frmThu.Owner = this;
                frmThu.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frmThu.ShowInTaskbar = false;
                frmThu.ShowDialog();
            }
            catch (Exception)
            {
                
            }
        }

        private void DeleteCommand_Thu_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Delete();
        }

        private void Delete()
        {
            try
            {
                var ret = MessageBox.Show("Bạn có chắc chắn muốn xóa phiếu đã chọn?", "Warning",
                                          MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                if (ret != MessageBoxResult.Yes) return;

                var objIncomingBO = new IncomingBO();
                foreach (var item in dgMain.SelectedItems)
                {
                    objIncomingBO.Delete(((tblPhieuThuChi) item).ID);
                }
                
                var lstThuChi = objIncomingBO.GetAll();

                dgMain.ItemsSource = lstThuChi;
            }
            catch (Exception)
            {

            }
        }

        private void AddCommand_Chi_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                var frmChi = new FrmThuChi(false);
                frmChi.Owner = this;
                frmChi.WindowStartupLocation = WindowStartupLocation.CenterOwner; 
                frmChi.ShowInTaskbar = false;
                frmChi.ShowDialog();
            }
            catch (Exception)
            {

            }
        }

        private void EditCommand_Chi_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                var objPhieuThuChi = (tblPhieuThuChi)dgMain.SelectedItem;
                if (objPhieuThuChi == null) return;

                var frmChi = new FrmThuChi(objPhieuThuChi, false);
                frmChi.Owner = this;
                frmChi.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frmChi.ShowInTaskbar = false;
                frmChi.ShowDialog();
            }
            catch (Exception)
            {

            }
        }

        private void DeleteCommand_Chi_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Delete();
            //var ret = MessageBox.Show("Bạn có chắc chắn muốn xóa phiếu chi đã chọn?", "Warning",
            //                              MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
            //if (ret != MessageBoxResult.Yes) return;

            //var objIncomingBO = new IncomingBO();
            //foreach (var item in dgMain.SelectedItems)
            //{
            //    objIncomingBO.Delete(((tblPhieuThuChi)item).ID);
            //}

            //var lstThuChi = objIncomingBO.GetAll();

            //dgMain.ItemsSource = lstThuChi;
        }

        private void SearchCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                var objBO = new IncomingBO();
                switch (cboSearchType.Text)
                {
                    case "Tên":
                        dgMain.ItemsSource = objBO.SearchByName(txtKeyword.Text.Trim());
                        break;
                    case "Ngày tháng":
                        var culture = new CultureInfo("vi-VN");

                        try
                        {
                            Convert.ToDateTime(txtKeyword.Text.Trim(), culture);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Ngày tháng không đúng định dạng dd/mm/yyyy (ngày/tháng/năm).", "Lỗi", MessageBoxButton.OK,
                                            MessageBoxImage.Error);
                            return;
                        }
                        dgMain.ItemsSource = objBO.SearchByDate(Convert.ToDateTime(txtKeyword.Text.Trim(), culture));
                        break;
                }
            }
            catch (Exception)
            {
                
            }
        }

        private void ApplicationMain_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            // Click main menu, do nothing ...
        }

        private void dgMain_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            try
            {
                if (dgMain.SelectedItems.Count > 0)
                {
                    if(dgMain.SelectedItems.Count == 1)
                    {
                        var objThuChi = (tblPhieuThuChi) dgMain.SelectedItem;
                        if (objThuChi.IsIncoming)
                        {
                            btnEditThu.IsEnabled = true;
                            btnEditChi.IsEnabled = false;
                        }
                        else
                        {
                            btnEditThu.IsEnabled = false;
                            btnEditChi.IsEnabled = true;
                        }
                    }
                    else
                    {
                        btnEditThu.IsEnabled = false;
                        btnEditChi.IsEnabled = false;
                    }
                    btnDeleteThu.IsEnabled = true;
                    btnDeleteChi.IsEnabled = true;
                }
                else
                {
                    btnEditThu.IsEnabled = false;
                    btnDeleteThu.IsEnabled = false;
                                        
                    btnEditChi.IsEnabled = false;
                    btnDeleteChi.IsEnabled = false;
                }
            }
            catch (Exception)
            {
                
            }
        }

        private void dgMain_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (dgMain.SelectedItems.Count == 1)
                {
                    var objPhieuThuChi = (tblPhieuThuChi)dgMain.SelectedItem;
                    if (objPhieuThuChi == null) return;

                    var frmThu = new FrmThuChi(objPhieuThuChi, objPhieuThuChi.IsIncoming);
                    frmThu.Owner = this;
                    frmThu.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    frmThu.ShowInTaskbar = false;
                    frmThu.ShowDialog();
                }
            }
            catch (Exception)
            {
                
            }
        }

        private void PopulateCombobox()
        {
            var searchTypes = new List<RibbonComboBoxItem>();
            // Add items
            var name = new RibbonComboBoxItem {Content = "Tên"};
            searchTypes.Add(name);
            var date = new RibbonComboBoxItem {Content = "Ngày tháng"};
            searchTypes.Add(date);

            cboSearchType.ItemsSource = searchTypes;
            cboSearchType.SelectedIndex = 0;
        }

        private void cboSearchType_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            try
            {
                cboSearchType.Text = ((RibbonComboBoxItem)cboSearchType.SelectedItem).Content.ToString();
            }
            catch (Exception)
            {
                
            }
        }

        private void ApplicationExit(object sender, ExecutedRoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// Import data from excel file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExcelImport(object sender, ExecutedRoutedEventArgs e)
        {
            var excelConn = new OleDbConnection();
            try
            {
                string fileName = string.Empty;
                var dlg = new OpenFileDialog
                {
                    DefaultExt = ".xls",
                    Filter = "Excel file (.xls)|*.xls"
                };

                if (dlg.ShowDialog() == true)
                {
                    fileName = dlg.FileName;
                }

                if (string.IsNullOrEmpty(fileName)) return;

                // Create connection to excel file
                excelConn.ConnectionString = BuildExcelConnString(fileName);
                var da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", excelConn);

                // Open connection
                excelConn.Open();

                // Fill data to a datatable
                var dt = new DataTable();
                da.Fill(dt);

                var objBO = new IncomingBO();

                if (dt.Rows.Count >0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        var ret = ImportRow(objBO, row);
                        if(!ret)
                        {
                            break;
                        }
                    }
                    LoadData();
                }
            }
            catch (Exception)
            {
                
            }
            finally
            {
                excelConn.Close();
            }
        }

        private bool ImportRow(IncomingBO objBO, DataRow row)
        {
            try
            {
                var objPhieuThuChi = new tblPhieuThuChi();

                objPhieuThuChi.QuyenSo = Convert.ToInt32(row["QuyenSo"].ToString());
                objPhieuThuChi.PhieuSo = Convert.ToInt32(row["PhieuSo"].ToString());
                objPhieuThuChi.NgayThang = Convert.ToDateTime(row["NgayThang"].ToString());
                objPhieuThuChi.TKNo = Convert.ToInt32(row["TKNo"].ToString());
                objPhieuThuChi.TKCo = Convert.ToInt32(row["TKCo"].ToString());
                objPhieuThuChi.TKThue = Convert.ToInt32(row["TKThue"].ToString());
                objPhieuThuChi.Thue = Convert.ToInt32(row["Thue"].ToString());
                objPhieuThuChi.HoTen = row["HoTen"].ToString();
                objPhieuThuChi.DiaChi = row["DiaChi"].ToString();
                objPhieuThuChi.LyDo = row["LyDo"].ToString();
                objPhieuThuChi.Sotien = Convert.ToInt32(row["Sotien"].ToString());
                objPhieuThuChi.VietBangChu = row["VietBangChu"].ToString();
                objPhieuThuChi.KemTheo = row["KemTheo"].ToString();
                objPhieuThuChi.DaNhanDu = row["DaNhanDu"].ToString();
                objPhieuThuChi.IsIncoming = Convert.ToBoolean(row["IsIncoming"].ToString());

                var ret = objBO.Insert(objPhieuThuChi);

                if (ret == Constants.Errors.EXISTED)
                {
                    var result = MessageBox.Show(this,
                                    "Phiếu số: " + objPhieuThuChi.PhieuSo + ", Quyển số: " + objPhieuThuChi.QuyenSo +
                                    " đã tồn tại, bạn có muốn cập nhật phiếu này không?", "Chú ý",
                                    MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);

                    switch (result)
                    {
                        case MessageBoxResult.Yes:
                            objBO.Update(objPhieuThuChi);
                            break;
                        case MessageBoxResult.No:
                            return true;
                        case MessageBoxResult.Cancel:
                            return false;
                    }
                }
                return true;
            }
            catch (Exception)
            {
                MessageBox.Show("Có lỗi xảy ra khi nhập file tại Phiếu số: " + row["PhieuSo"] + ", Quyển số: " + row["QuyenSo"], "Lỗi", MessageBoxButton.OK,
                                MessageBoxImage.Error);
                return false;
            }
        }

        /// <summary>
        /// Export data to excel file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExcelExport(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                Microsoft.Office.Interop.Excel._Application app = null;
                try
                {
                    string fileName = string.Empty;
                    var dlg = new SaveFileDialog
                    {
                        FileName = DateTime.Now.ToString("ddMMyyyy_hhMMss"),
                        DefaultExt = ".xls",
                        Filter = "Excel file (.xls)|*.xls"
                    };

                    if (dlg.ShowDialog() == true)
                    {
                        fileName = dlg.FileName;
                    }

                    if (string.IsNullOrEmpty(fileName)) return;

                    // creating Excel Application
                    app = new Microsoft.Office.Interop.Excel.Application();

                    // creating new WorkBook within Excel application
                    Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);

                    // creating new Excelsheet in workbook
                    Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

                    // get the reference of first sheet. By default its name is Sheet1.
                    // store its reference to worksheet
                    worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets["Sheet1"];
                    worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;

                    // changing the name of active sheet
                    //worksheet.Name = "Exported";

                    var properties = new tblPhieuThuChi().GetType().GetProperties();

                    // storing header part in Excel
                    for (int i = 0; i < properties.Length; i++)
                    {
                        worksheet.Cells[1, i + 1] = properties[i].Name;
                    }

                    // storing Each row and column value to excel sheet
                    for (int i = 0; i < _lstThuChi.Count; i++)
                    {
                        for (int j = 0; j < properties.Length; j++)
                        {
                            worksheet.Cells[i + 2, j + 1] = GetObjectValue(_lstThuChi[i], properties[j].Name);
                        }
                    }

                    // save the application
                    workbook.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing,
                                    Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                    MessageBox.Show("Xuất file Excel thành công.", "Thông báo", MessageBoxButton.OK,
                                    MessageBoxImage.Information);
                }
                catch (Exception)
                {
                    MessageBox.Show("Có lỗi xảy ra khi xuất file Excel.", "Lỗi", MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                }
                finally
                {
                    // Exit from the application
                    if (app != null) app.Quit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Get property value base on property name
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        private static string GetObjectValue(object obj, string propertyName)
        {
            try
            {
                var type = obj.GetType();
                var info = type.GetProperty(propertyName);
                return info == null ? string.Empty : info.GetValue(obj, null).ToString();
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Create connection string to Excel file
        /// </summary>
        /// <param name="excelFilePath"></param>
        /// <returns></returns>
        public static string BuildExcelConnString(string excelFilePath)
        {
            var csb = new OleDbConnectionStringBuilder
                          {
                              DataSource = excelFilePath,
                              Provider="Microsoft.ACE.OLEDB.12.0"
                              //Provider = "Microsoft.Jet.OLEDB.4.0"
                          };
            csb.Add("Extended Properties", "Excel 8.0;HDR=YES;IMEX=1");
            return csb.ToString();
        }

        private void dgMain_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Delete)
                    Delete();
            }
            catch (Exception)
            {
                
            }
        }

        private void ApplicationConfig(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                var frmCompany = new FrmOptions();
                frmCompany.Owner = this;
                frmCompany.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frmCompany.ShowInTaskbar = false;
                frmCompany.ShowDialog();
            }
            catch (Exception)
            {
                
            }
        }

        private void AccountBalance(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                var frmCompany = new FrmAccountBalance();
                frmCompany.Owner = this;
                frmCompany.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frmCompany.ShowInTaskbar = false;
                frmCompany.ShowDialog();
            }
            catch (Exception)
            {

            }
        }
    }
}
